package service

import (
	"api/cache"
	"api/model"
	"api/serializer"
	"api/util"
	"encoding/json"
	"time"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

// UserLoginService 管理用户登录的服务
type UserLoginService struct {
	UserName string `form:"user_name" json:"user_name" binding:"required,min=5,max=30"`
	Password string `form:"password" json:"password" binding:"required,min=8,max=40"`
}

// setSession 设置session
func (service *UserLoginService) setSession(c *gin.Context, user model.User) {
	s := sessions.Default(c)
	s.Clear()
	s.Set("user_id", user.ID)
	s.Save()
}

// setCookie 设置用户cookie
func (service *UserLoginService) setCookie(c *gin.Context, usertoken string) {
	c.SetCookie("user_token", usertoken, 3600, "/", "localhost", false, true)
}

// cacheUser 缓存用户信息
func (service *UserLoginService) cacheUser(user model.User) (string, error) {
	uid, err := uuid.NewUUID()

	if err != nil {
		util.Log().Panic("UUID生成失败", err)
	}

	userToken := uid.String()

	jsonByte, err := json.Marshal(serializer.BuildUser(user))

	if err != nil {
		util.Log().Panic("UserLoginService.cacheUser:json转换失败", err)
	}

	if err := cache.RedisClient.Set(userToken, jsonByte, time.Hour*2).Err(); err != nil {
		util.Log().Panic("UserLoginService.cacheUser:缓存写入失败", err)
		return "", err
	}

	return userToken, nil
}

// Login 用户登录函数
func (service *UserLoginService) Login(c *gin.Context) serializer.Response {
	var user model.User

	if err := model.DB.Preload("Permissions").Where("user_name = ?", service.UserName).First(&user).Error; err != nil {
		return serializer.ParamErr("账号或密码错误", nil)
	}

	if user.CheckPassword(service.Password) == false {
		return serializer.ParamErr("账号或密码错误", nil)
	}

	// 设置session
	//service.setSession(c, user)

	// 设置缓存
	token, err := service.cacheUser(user)
	if err != nil {
		return serializer.RedisErr("userToken写入失败", err)
	}

	service.setCookie(c, token)

	return serializer.BuildUserResponse(user)
}
